<template>
  <div class="cases-page">
    <div class="card">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增案件
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-select
            v-model="searchForm.status"
            placeholder="案件状态"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
          <el-select
            v-model="searchForm.priority"
            placeholder="优先级"
            clearable
            style="width: 100px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索案件标题、编号"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="caseNumber" label="案件编号" width="140" />
        <el-table-column prop="title" label="案件标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="案件类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" class="status-tag">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)" class="priority-tag">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clientName" label="客户" width="120" />
        <el-table-column prop="lawyerName" label="负责律师" width="120" />
        <el-table-column prop="amount" label="案件金额" width="120">
          <template #default="{ row }">
            <span v-if="row.amount">{{ formatMoney(row.amount) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.startDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 案件表单对话框 -->
    <CaseForm
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCaseList, deleteCase } from '@/api/case'
import { formatDate, formatMoney } from '@/utils'
import type { Case, Pagination } from '@/types'
import CaseForm from './components/CaseForm.vue'

const router = useRouter()
const loading = ref(false)
const selectedIds = ref<string[]>([])
const tableData = ref<Case[]>([])
const formVisible = ref(false)
const formData = ref<Partial<Case>>({})

const searchForm = reactive({
  keyword: '',
  status: '',
  priority: ''
})

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
})

// 获取案件列表
const fetchCaseList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    const data = await getCaseList(params)
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取案件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCaseList()
}

// 选择变化
const handleSelectionChange = (selection: Case[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增案件
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 查看案件
const handleView = (row: Case) => {
  router.push(`/cases/detail/${row.id}`)
}

// 编辑案件
const handleEdit = (row: Case) => {
  formData.value = { ...row }
  formVisible.value = true
}

// 删除案件
const handleDelete = async (row: Case) => {
  try {
    await ElMessageBox.confirm(`确定要删除案件 "${row.title}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCase(row.id)
    ElMessage.success('删除成功')
    fetchCaseList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个案件吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(selectedIds.value.map(id => deleteCase(id)))
    ElMessage.success('批量删除成功')
    fetchCaseList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchCaseList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchCaseList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchCaseList()
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return textMap[status] || status
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const typeMap: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return textMap[priority] || priority
}

onMounted(() => {
  fetchCaseList()
})
</script>

<style lang="scss" scoped>
.cases-page {
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
